Ext.define("MyApp.controller.Retrieve",{
    extend: "Ext.app.Controller",
	config: {
		views: [
			'RetrieveKey'
		],
		control: {
			'retrievekey button#retrieve': {
				tap: "onRetrieve"
			}
		
		}
	},
	
	onRetrieve: function() {
		var user = Ext.ComponentQuery.query('retrievekey textfield[itemId="username"]').pop();
		var pass = Ext.ComponentQuery.query('retrievekey textfield[itemId="password"]').pop();
		if (user == null || pass == null || user === '' || pass === ''){
			alert("Credentials Missing","Please enter a username and password");
		}
		else {
			Ext.Ajax.request({
				url: 'http://appt.elasticbeanstalk.com/retrieve.php',
				method: 'POST',				
				params: {username: user, password: pass},
				success: function(response){
					var text = response.responseText;
					var data = Ext.JSON.decode(response.responseText.trim());
					
					if (data.deviceID == null || data.id == null || data.deviceID === '' || data.id === ''){
						alert("Device Not Found","No device was found with these credentials. Please try again.")
					}
					else {
						var storage = window.localStorage;
						storage.setItem("AppointmentKey",data.deviceID);
						storage.setItem("UserID",data.id);
						storage.setItem("timezone",data.timezone);
						
						
						Ext.Viewport.setActiveItem('appointmentlist',{type:'slide', direction:'left'});
						App.dispatch({controller:"Appointment",action:"appointmentListLoad"});
						
					}
				},
				failure: function(response){
							Ext.Msg.alert('error', 'error submitting appointment');
							console.log(response.responseText);
				}
			
		
			});
		}
	}
});